package com.qbw.app.module.vehicle.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.qbw.actionmanager.ActionManager;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.action.AddVehicleAction;
import com.qbw.app.action.ScanAction;
import com.qbw.app.databinding.VehicleActivityAddBinding;
import com.qbw.app.model.Vehicle;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.util.HttpRequestUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.module.main.activity.MainActivity;
import com.qbw.app.module.user.activity.UserLoginRegistActivity;
import com.qbw.app.request.impl.VehicleRequest;

import cn.jpush.android.api.JPushInterface;

/**
 * @author QBW
 * @date 2019/9/24
 */
public class VehicleAddActivity extends CommonActivity<VehicleActivityAddBinding> implements View.OnFocusChangeListener {

    public static final int TYPE_FROM_DEFAULT = 0;
    /**
     * 注册或者登录之后，没有车辆的情况下，会跳转到此页面
     */
    public static final int TYPE_FROM_NO_VEHICLE = 1;

    private int mType;
    private Vehicle mVehicle = new Vehicle();

    public static final String SCAN_TYPE_VIN = VehicleAddActivity.class.getSimpleName() + "_vin";
    public static final String SCAN_TYPE_ENGINE = VehicleAddActivity.class.getSimpleName() + "_engine";

    public static void start(Context context) {
        start(context, TYPE_FROM_DEFAULT);
    }

    public static void start(Context context, int type) {
        Intent intent = new Intent(context, VehicleAddActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_TYPE, type);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.vehicle_activity_add;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
        mType = args.getInt(Constant.KEY_TYPE);
        mBinding.title.setListener(this);
        mBinding.setVehicle(mVehicle);
        mBinding.ivScanVin.setOnClickListener(this);
        mBinding.ivScanNumberEngine.setOnClickListener(this);
        mBinding.tvSure.setOnClickListener(this);
        mBinding.etVin.setOnFocusChangeListener(this);
        ActionManager.getInstance().addInterestedAction(this, ScanAction.class);
        if (mType == TYPE_FROM_NO_VEHICLE) {
            UniversalToastUtil.showToast(ResUtil.getString(R.string.please_add_vehicle), 3000);
        }
    }

    @Override
    public void onLeftAreaClick() {
        if (mType == TYPE_FROM_NO_VEHICLE) {
            // 注销账号
            mGeneralManager.getRequestManager()
                    .getCommonRequest()
                    .stopPush(JPushInterface.getRegistrationID(this), null)
                    .execute();
            mGeneralManager.getUserManager().logout();

            UserLoginRegistActivity.start(this);
        }
        super.onLeftAreaClick();
    }

    @Override
    public void onBackPressed() {
        onLeftAreaClick();
    }

    private boolean checkInput() {
        if (TextUtils.isEmpty(mVehicle.getVehicleVin())) {
            UniversalToastUtil.showToast(R.string.vehicle_vin_please);
            return false;
        } else if (TextUtils.isEmpty(mVehicle.getEngineNumber())) {
            UniversalToastUtil.showToast(R.string.engine_number_hint);
            return false;
        } else if (TextUtils.isEmpty(mVehicle.getVehicleNick())) {
            UniversalToastUtil.showToast(R.string.vehicle_name_hint);
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int vid = v.getId();
        if (vid == R.id.tv_sure) {
            if (!checkInput()) {
                return;
            }
            showLoadingDialog("");
            mGeneralManager.getRequestManager()
                           .getVehicleRequest()
                           .addVehicle(mVehicle.getVehicleVin(),
                                       mVehicle.getVehicleNick(),
                                       mVehicle.getEngineNumber(),
                                       this)
                           .execute();
        } else if (vid == R.id.iv_scan_vin) {
            VehicleAddByScanActivity.start(this, SCAN_TYPE_VIN);
        } else if (vid == R.id.iv_scan_number_engine) {
            VehicleAddByScanActivity.start(this, SCAN_TYPE_ENGINE);
        }
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(VehicleRequest.METHOD_VEHICLE_ADD)) {
            ActionManager.getInstance()
                         .triggerAction(new AddVehicleAction(new Vehicle(mVehicle.getVehicleNick(),
                                                                         mVehicle.getVehicleVin())));
            closeLoadingDialog();
            if (mType == TYPE_FROM_NO_VEHICLE) {
                MainActivity.start(this);
            }
            finish();
        } else if (method.equals(VehicleRequest.METHOD_VEHICLE_DETAIL_BY_VIN)) {
            Vehicle.ResponseOne res = (Vehicle.ResponseOne) entity;
            Vehicle vehicle = res.getData();
            vehicle.setVehicleVin(mVehicle.getVehicleVin());
            vehicle.setEngineNumber(mVehicle.getEngineNumber());
            vehicle.setVehicleNick(mVehicle.getVehicleNick());
            mVehicle = vehicle;
            mBinding.setVehicle(mVehicle);
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        message = HttpRequestUtil.getMessage(errorCode, message);
        String method = httpTask.getMethod();
        if (method.equals(VehicleRequest.METHOD_VEHICLE_ADD)) {
            UniversalToastUtil.showFailedIconToast(message);
            closeLoadingDialog();
        }
    }

    @Override
    public void onActionTriggered(Object action) {
        super.onActionTriggered(action);
        if (action instanceof ScanAction) {
            ScanAction scanAction = (ScanAction) action;
            if (scanAction.getType().equals(SCAN_TYPE_VIN)) {
                mVehicle.setVehicleVin(scanAction.getAction());
                mBinding.executePendingBindings();
                int len = mBinding.etVin.getText().length();
                if (len > 0) {
                    mBinding.etVin.setSelection(len);
                    mBinding.etVin.requestFocus();
                }
                mGeneralManager.getRequestManager()
                               .getVehicleRequest()
                               .getVehicleDetailByVin(mVehicle.getVehicleVin(), this)
                               .execute();
            } else if (scanAction.getType().equals(SCAN_TYPE_ENGINE)) {
                mVehicle.setEngineNumber(scanAction.getAction());
                mBinding.executePendingBindings();
                int len = mBinding.etEngineNumber.getText().length();
                if (len > 0) {
                    mBinding.etEngineNumber.setSelection(len);
                    mBinding.etEngineNumber.requestFocus();
                }
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(Constant.KEY_TYPE, mType);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActionManager.getInstance().removeInterestedActions(this);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int vid = v.getId();
        if (vid == R.id.et_vin) {
            if (!hasFocus) {
                mGeneralManager.getRequestManager()
                               .getVehicleRequest()
                               .getVehicleDetailByVin(mVehicle.getVehicleVin(), this)
                               .execute();
            }
        }
    }
}
